package com.jxd.ordering.handle;

import com.jxd.ordering.model.Entity;
import com.jxd.ordering.model.ResultBody;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.List;
import java.util.Map;

/**
 * @ClassName ResponseAdvice
 * @Description TODO
 * @Author Ankailong
 * @Date 2022/9/29
 * @Version 1.0
 */
@RestControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //拦截响应，封装响应体

        //已经封装过响应体
        if (body instanceof ResultBody) {
            return body;
        }

        //正常响应，响应数据为map、list、实体类或包装类
        if (body instanceof Map && ((Map)body).get("status") == null || body instanceof List
                || body instanceof Entity || body instanceof String || body instanceof Number || body instanceof Boolean
                || body instanceof Character || body == null
        ) {
            return ResultBody.success(body);
        }

        //系统响应
        if (body instanceof Map && "200".equals(((Map)body).get("status"))) {//成功响应
            return ResultBody.success(body);
        } else if (body instanceof Map) {//失败响应
            return ResultBody.error(((Map)body).get("status").toString(), ((Map)body).get("message").toString());
        } else {//其余情况
            return ResultBody.error("-1" ,"服务器响应时间过长");
        }
    }
}
